package com.ledim.share;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import com.ledim.bean.LedimAccountBean;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.ToastUtil;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.exception.WeiboException;

/**
 * Created by ccx on 16/5/26.
 */
public abstract class LeDimAuthListner implements WeiboAuthListener {

    private Context mContext;

    public LeDimAuthListner(Context context) {
        mContext = context;
    }

    @Override
    public void onComplete(Bundle values) {
        Oauth2AccessToken mAccessToken = Oauth2AccessToken.parseAccessToken(values);
        if (mAccessToken.isSessionValid()) {
            LedimAccountBean account = new LedimAccountBean();
            account.auth_key = ConstantUtil.ShareConstant.SINA_APP_KEY;
            account.auth_token = mAccessToken.getToken();
            account.expires = mAccessToken.getExpiresTime() + "";
            account.user_id = mAccessToken.getUid();
            account.platform = ConstantUtil.AccountType.WEIBO;

            //ToastUtil.toastShow(mContext, "微博登录\nauth_key:" + Config.SINA_APP_KEY + "\nauth_token:" + mAccessToken.getToken() + "\nexpires:" + mAccessToken.getExpiresTime() + "\nuser_id:" + mAccessToken.getUid());
            // 保存 Token 到 SharedPreferences
            onSuccess(account.platform, account.auth_token, account.user_id);
            AccessTokenKeeper.writeAccessToken(mContext, mAccessToken);
        } else {
            String code = values.getString("code");
            String message = "授权失败";
            if (!TextUtils.isEmpty(code)) {
                message = message + "\nObtained the code: " + code;
            }
            ToastUtil.toast(message);
        }
    }

    @Override
    public void onCancel() {
        ToastUtil.toast("取消授权");
    }

    @Override
    public void onWeiboException(WeiboException e) {
        ToastUtil.toast("Auth exception : " + e.getMessage());
    }

    /**
     * 若需要授权登录则实现
     *
     * @param platform
     * @param auth_token
     * @param user_id
     */
    public abstract void onSuccess(int platform, String auth_token, String user_id);
}
